package com.yearner.reviewplan.manage.system;

import com.yearner.reviewplan.common.aspect.AuthTokenV1;
import com.yearner.reviewplan.common.model.Result;
import com.yearner.reviewplan.manage.system.bean.MenuVo;
import com.yearner.reviewplan.manage.system.entity.UserPerm;
import com.yearner.reviewplan.manage.system.service.UserPermService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 权限表
 *
 * @author Pengyg
 * @since 2020-01-13
 */
@Api
@RestController
@RequestMapping("api/system/userperm")
public class UserPermController {
    @Autowired
    private UserPermService service;

    private boolean updateMenu = false;
    private List<MenuVo> menuVoList;
    /**
     * 列表
     */
    @GetMapping("/list")
    @AuthTokenV1
    public Result list(@RequestParam Map<String, Object> params){
        updateList();
        return Result.success(this.menuVoList);
    }

    @GetMapping("/selectTree")
    @AuthTokenV1
    @ApiOperation(value = "selectTree")
    public Result selectTree(){
        updateList();
        MenuVo menuVo = new MenuVo();
        menuVo.setChildren(this.menuVoList);
        menuVo.setTitle("Root");
        List<MenuVo> tree = new ArrayList<>();
        tree.add(menuVo);
        return Result.success(tree);
    }


    /**
     * 信息详情
     */
    @GetMapping("/info/{id}")
    @AuthTokenV1
    public Result info(@PathVariable("id") Integer id){
        updateList();
        MenuVo aside = service.getMenuInList(menuVoList, id);
        return Result.success(aside);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @AuthTokenV1
    public Result save(@RequestBody MenuVo entity){
        UserPerm perm = entity.getUserPerm();
        service.save(perm);
        updateMenu = true;
        return Result.success();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @AuthTokenV1
    public Result update(@RequestBody MenuVo entity){
		service.updateById(entity.getUserPerm());
        updateMenu = true;
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    @AuthTokenV1
    public Result delete(@RequestBody List<Integer> ids){
        // todo 锁定相关路由?
		service.deleteById(ids);
        updateMenu = true;
        return Result.success();
    }

    private void updateList() {
        if (updateMenu || menuVoList ==null) {
            this.menuVoList = service.getMenus();
            updateMenu = false;
        }
    }

    public List<MenuVo> getMenuVoList() {
        updateList();
        return menuVoList;
    }
}
